import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'
import { useUserStore } from '@/stores/user'
import { hasPermission } from '@/utils/route'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    name: '首页',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '系统看板', icon: 'HomeFilled' }
      }
    ]
  },
  // 位置管理相关路由
  {
    path: '/location',
    component: Layout,
    redirect: '/location/list',
    name: 'Location',
    meta: { title: '位置管理', icon: 'Location' },
    children: [
      {
        path: 'list',
        name: 'LocationList',
        component: () => import('@/views/location/list.vue'),
        meta: { title: '位置列表' }
      },
      {
        path: 'type',
        name: 'LocationType',
        component: () => import('@/views/location/type.vue'),
        meta: { title: '位置类型' }
      },
      {
        path: 'add',
        name: 'LocationAdd',
        component: () => import('@/views/location/edit.vue'),
        meta: { title: '添加位置' }
      },
      {
        path: 'edit/:id',
        name: 'LocationEdit',
        component: () => import('@/views/location/edit.vue'),
        meta: { title: '编辑位置', hidden: true }
      }
    ]
  },
  // 系统管理相关路由
  {
    path: '/system',
    component: Layout,
    redirect: '/system/admin',
    name: 'System',
    meta: { 
      title: '系统管理',
      icon: 'Setting',
      roles: ['admin', 'editor'] // 只允许超级管理员和普通管理员访问
    },
    children: [
      {
        path: 'admin',
        name: 'Admin',
        component: () => import('@/views/admin/index.vue'),
        meta: { 
          title: '管理员',
          icon: 'User',
          roles: ['admin'] // 仅允许系统管理员访问
        }
      },
      {
        path: 'icon',
        name: 'IconManagement',
        component: () => import('@/views/system/icon/index.vue'),
        meta: { 
          title: '图标管理',
          icon: 'Picture',
          roles: ['admin'] // 仅允许系统管理员访问
        }
      },
      {
        path: 'config',
        name: 'SystemConfig',
        component: () => import('@/views/system/config.vue'),
        meta: { title: '系统设置', roles: ['admin'] }
      },
      {
        path: 'log',
        name: 'OperationLog',
        component: () => import('@/views/system/log.vue'),
        meta: { title: '操作日志', roles: ['admin'] }
      }
    ]
  },
  // 个人中心路由
  {
    path: '/profile',
    component: Layout,
    redirect: '/profile/index',
    meta: { hidden: true },
    children: [
      {
        path: 'index',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人中心' }
      }
    ]
  },
  // 旅游攻略管理路由
  {
    path: '/travel-guide',
    component: Layout,
    name: 'TravelGuide',
    meta: { title: '旅游攻略管理', icon: 'guide' },
    children: [
      {
        path: 'index',
        name: 'TravelGuideIndex',
        component: () => import('@/views/travel-guide/index.vue'),
        meta: { title: '旅游攻略管理' }
      }
    ]
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', hidden: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  document.title = to.meta.title ? `${to.meta.title} - 沙扒湾旅游管理系统` : '沙扒湾旅游管理系统'
  
  // 简化登录逻辑，检查localStorage中是否有用户名
  const username = localStorage.getItem('username')
  const userStore = useUserStore()
  
  // 未登录状态
  if (!username) {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
    return
  }
  
  // 已登录状态
  if (to.path === '/login') {
    next('/')
    return
  }
  
  // 已有用户信息，检查权限
  if (userStore.name) {
    if (to.meta.roles) {
      // 判断用户角色是否有权限访问
      if (hasPermission(userStore.roles, to)) {
        next()
      } else {
        // 无权限，跳转到首页
        next('/dashboard')
      }
    } else {
      next()
    }
    return
  }
  
  // 没有用户信息，从localStorage加载
  try {
    await userStore.getUserInfo()
    
    // 检查权限
    if (to.meta.roles) {
      if (hasPermission(userStore.roles, to)) {
        next()
      } else {
        next('/dashboard')
      }
    } else {
      next()
    }
  } catch (error) {
    // 获取用户信息失败，清除状态并跳转到登录页
    userStore.resetState()
    next('/login')
  }
})

export default router 